package msgo

import "strings"

type treeNode struct {
	name       string
	children   []*treeNode
	routerName string
	inEnd      bool
}

// put path: /user/get/:id
func (t *treeNode) Put(path string) {
	root := t
	paths := strings.Split(path, "/")
	for index, name := range paths {
		if index == 0 {
			continue
		}
		isMath := false
		children := t.children
		for _, node := range children {
			if node.name == name {
				isMath = true
				t = node
				break
			}
		}
		if !isMath {
			var isEnd bool
			if index == len(paths)-1 {
				isEnd = true
			}
			node := &treeNode{
				name:     name,
				children: make([]*treeNode, 0),
				inEnd:    isEnd,
			}
			children = append(children, node)
			t.children = children
			t = node
		}
	}
	t = root
}

func (t *treeNode) Get(path string) *treeNode {
	paths := strings.Split(path, "/")
	routerName := ""
	for index, name := range paths {
		if index == 0 {
			continue
		}
		children := t.children
		for _, node := range children {
			if node.name == name ||
				node.name == "*" ||
				strings.Contains(node.name, ":") {
				routerName += "/" + node.name
				node.routerName = routerName
				t = node
				//最后一个
				if index == len(paths)-1 {
					return node
				}
				break
			}
		}
	}
	return nil
}
